package app.qrcode.browser.todoapp.fragments.list

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.PopupMenu
import androidx.appcompat.widget.SearchView
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.*
import app.qrcode.browser.todoapp.App.Companion.appContext
import app.qrcode.browser.todoapp.R
import app.qrcode.browser.todoapp.common.ViewBindingFragment
import app.qrcode.browser.todoapp.data.models.ToDoData
import app.qrcode.browser.todoapp.data.viewmodel.ToDoViewModel
import app.qrcode.browser.todoapp.databinding.FragmentListBinding
import app.qrcode.browser.todoapp.fragments.SharedViewModel
import app.qrcode.browser.todoapp.fragments.list.adapter.ListAdapter
import app.qrcode.browser.todoapp.utils.hideKeyBoard
import com.google.android.material.snackbar.Snackbar
import jp.wasabeef.recyclerview.animators.SlideInUpAnimator

class ListFragment : ViewBindingFragment<FragmentListBinding>(), SearchView.OnQueryTextListener {

    private val mToDoViewModel: ToDoViewModel by activityViewModels()

    private val adapter: ListAdapter by lazy { ListAdapter(this) }

    private val mShareViewModel: SharedViewModel by activityViewModels()

    lateinit var searchView: SearchView

    override fun initView() {
        super.initView()
        setHasOptionsMenu(true)
        hideKeyBoard(requireActivity())
//        if (!adapter.hasObservers()) {
//            adapter.setHasStableIds(true)
//        }

        binding.recyclerView.adapter = adapter
//        adapter.listener = object : OnItemClickListener {
//            override fun onItemClick(viewHolder: RecyclerView.ViewHolder,view: View) {
//                var position = viewHolder.adapterPosition
//                val itemToUpdate = adapter.dataList[position]
//                showChangeTaskStatusPopUpMenu(view,itemToUpdate,position)
//                adapter.notifyItemChanged(position)
//            }
//        }
        binding.recyclerView.layoutManager =
            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.recyclerView.itemAnimator = SlideInUpAnimator().apply {
            addDuration = 300
        }
//        binding.recyclerView.itemAnimator = null
        swipeToDelete(binding.recyclerView)

        mShareViewModel.emptyDatabase.observe(viewLifecycleOwner, Observer {
            showEmptyDatabaseViews(it)
        })

        mToDoViewModel.getAllData.observe(viewLifecycleOwner, Observer { data ->
            mShareViewModel.checkIfDatabaseEmpty(data)
            adapter.setData(data)
        })

        binding.floatingActionButton.setOnClickListener {
            findNavController().navigate(R.id.action_listFragment_to_addFragment)
        }
    }
//    override fun onCreateView(
//        inflater: LayoutInflater, container: ViewGroup?,
//        savedInstanceState: Bundle?
//    ): View? {
//
//        // Inflate the layout for this fragment
//        return inflater.inflate(R.layout.fragment_list, container, false)
//    }

//    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//        super.onViewCreated(view, savedInstanceState)
//
//
//
//
//    }

    private fun showEmptyDatabaseViews(emptyDatabase: Boolean) {
        if (emptyDatabase) {
            binding.noDataImageView.visibility = View.VISIBLE
            binding.noDataTextView.visibility = View.VISIBLE
        } else {
            binding.noDataImageView.visibility = View.INVISIBLE
            binding.noDataTextView.visibility = View.INVISIBLE
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_delete_all -> {
                confirmRemoval()
//                if (!searchView.isIconified()) {
//                    searchView.onActionViewCollapsed()
//                }
            }
            R.id.menu_priority_high -> {
                mToDoViewModel.sortByHighPriority.observe(this, Observer {
                    adapter.setData(it)
                })
//                searchView.isFocusable = false
            }
//            if (!searchView.isIconified()) {
//                searchView.isIconified = true
//            }
            R.id.menu_priority_low -> {
                mToDoViewModel.sortByLowPriority.observe(this, Observer {
                    adapter.setData(it)
                })
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_taskStatus_high -> {
                mToDoViewModel.sortByHighTaskStatus.observe(this) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }

            R.id.menu_taskStatus_low -> {
                mToDoViewModel.sortByLowTaskStatus.observe(this) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_priority_high -> {
                mToDoViewModel.classifiedIntoHighPriority.observe(this) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_priority_medium -> {
                mToDoViewModel.classifiedIntoMediumPriority.observe(
                    this
                ) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_priority_low -> {
                mToDoViewModel.classifiedIntoLowPriority.observe(this) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_taskStatus_high -> {
                mToDoViewModel.classifiedIntoHighTaskStatus.observe(
                    this
                ) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_taskStatus_medium -> {
                mToDoViewModel.classifiedIntoMediumTaskStatus.observe(
                    this
                ) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_class_taskStatus_low -> {
                mToDoViewModel.classifiedIntoLowTaskStatus.observe(
                    this
                ) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
            R.id.menu_show_all -> {
                mToDoViewModel.getAllData.observe(this) {
                    adapter.setData(it)
                }
//                if (!searchView.isIconified()) {
//                    searchView.isIconified = true
//                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun confirmRemoval() {
        val builder = AlertDialog.Builder(requireContext())
        builder.setPositiveButton("Yes") { _, _ ->
            mToDoViewModel.deleteAll()
            Toast.makeText(
                requireContext(),
                "Successfully Removed Everything",
                Toast.LENGTH_SHORT
            ).show()
        }
        builder.setNegativeButton("No") { _, _ -> }
        builder.setTitle("Delete Everything?")
        builder.setMessage("Are you sure you want to remove Everything?")
        builder.create().show()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.list_fragment_menu, menu)
        val search = menu.findItem(R.id.menu_search)
        searchView = (search.actionView as? SearchView)!!
        searchView.setOnQueryTextListener(this)
    }


    private fun swipeToDelete(recyclerView: RecyclerView) {
        val swipeToDeleteCallback = object : SwipeToDelete() {
            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val itemToDelete = adapter.dataList[viewHolder.adapterPosition]
                mToDoViewModel.deleteItem(itemToDelete)
                adapter.notifyItemRemoved(viewHolder.adapterPosition)
                restoreDeleteData(viewHolder.itemView, itemToDelete, viewHolder.adapterPosition)
            }
        }
        val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallback)
        itemTouchHelper.attachToRecyclerView(recyclerView)
    }

    private fun restoreDeleteData(view: View, deletedItem: ToDoData, position: Int) {
        val snackbar = Snackbar.make(view, "Deleted '${deletedItem.title}'", Snackbar.LENGTH_LONG)
        snackbar.setAction("Undo") {
            mToDoViewModel.insertData(deletedItem)
        }
        snackbar.show()
    }

    override fun onQueryTextSubmit(query: String?): Boolean {
        if (query != null) {
            searchThroughDatabase(query)
        }
        return true
    }


    override fun onQueryTextChange(query: String?): Boolean {
        if (query != null) {
            searchThroughDatabase(query)
        }
        return true
    }


    private fun searchThroughDatabase(query: String) {
        val searchQuery = "%$query%"

        mToDoViewModel.searchDatabase(searchQuery).observe(this, Observer { list ->
            list?.let {
                adapter.setData(it)
            }
        })

    }

    fun showChangeTaskStatusPopUpMenu(view: View, data: ToDoData, position: Int) {
        var popupMenu = PopupMenu(this.requireActivity(), view)
        popupMenu.menuInflater.inflate(R.menu.update_task_status_menu, popupMenu.menu)
        popupMenu.show()
        popupMenu.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.menu_taskStatus_todo -> {
                    mToDoViewModel.updateTaskStatus(
                        data.id,
                        mShareViewModel.parseTaskStatus(item.title.toString())
                    )
                    Log.w("gyk", "ListAdapter.showChangeTaskStatusPopUpMenu ->修改为todo")
                }
                R.id.menu_taskStatus_quarlifyinstance -> {
                    mToDoViewModel.updateTaskStatus(
                        data.id,
                        mShareViewModel.parseTaskStatus(item.title.toString())
                    )
                    Log.w("gyk", "ListAdapter.showChangeTaskStatusPopUpMenu ->修改为qual ")
                }
                R.id.menu_taskStatus_done -> {
                    mToDoViewModel.updateTaskStatus(
                        data.id,
                        mShareViewModel.parseTaskStatus(item.title.toString())
                    )
                    Log.w("gyk", "ListAdapter.showChangeTaskStatusPopUpMenu ->修改为done ")
                }
            }
            true
        }
    }

}